package controller;

import common.Result;
import common.ResultCodeEnum;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.vo.UserCenterVo;
import service.NewsHeadlineService;
import service.UserCenterService;
import service.impl.NewsHeadlineServiceImpl;
import service.impl.UserCenterServiceImpl;
import util.JwtHelper;
import util.WebUtil;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

@WebServlet("/center/*")
public class UserCenterController extends BaseController {
    private UserCenterService centerService = new UserCenterServiceImpl();



    // 获取个人中心信息
    protected void info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");
        if (token == null || JwtHelper.isExpiration(token)) {
            WebUtil.writeJson(resp, Result.build(null, ResultCodeEnum.NOTLOGIN));
            return;
        }
        Integer userId = JwtHelper.getUserId(token).intValue();
        UserCenterVo centerInfo = centerService.getUserCenterInfo(userId);
        Map<String, Object> data = new HashMap<>();
        data.put("centerInfo", centerInfo);
        WebUtil.writeJson(resp, Result.ok(data));
    }

    private NewsHeadlineService headlineService=new NewsHeadlineServiceImpl();
// 分页查询用户发布的头条
    protected void getPublishedPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");
        if (token == null || JwtHelper.isExpiration(token)) {
            WebUtil.writeJson(resp, Result.build(null, ResultCodeEnum.NOTLOGIN));
            return;
        }

        Integer userId = JwtHelper.getUserId(token).intValue();
        int pageNum = Integer.parseInt(req.getParameter("pageNum"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        Map pageInfo = headlineService.findByPublisherPage(userId, pageNum, pageSize);
        Map data = new HashMap<>();
        data.put("pageInfo", pageInfo);
        WebUtil.writeJson(resp, Result.ok(data));
    }

}